package com.baizhi.cmfz.service.impl;

import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.entity.CmfzAdmin;
import com.baizhi.cmfz.entity.CmfzBanner;
import com.baizhi.cmfz.mapper.CmfzAdminMapper;

import com.baizhi.cmfz.service.CmfzAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@Transactional
public class CmfzAdminServiceImpl implements CmfzAdminService {

    @Autowired
    private CmfzAdminMapper am;

    @Override
    public CmfzAdmin selectByNameAndPwd(String username, String password) {
        return am.selectByNameAndPwd(username,password);
    }

    @Override
    public Page<CmfzAdmin> selectAllByPage(Integer page, Integer limit) {
        Page<CmfzAdmin> page1 = new Page<>(page, limit);
        Page<CmfzAdmin> adminPage = am.selectPage(page1, null);
        return adminPage;
    }

    @Override
    @LogAnnotation(type = "insert",value = "添加管理员")
    public void insertAdmin(CmfzAdmin admin) {
        String salt = UUID.randomUUID().toString().substring(0, 4);
        admin.setSalt(salt);
        Md5Hash md5Pwd = new Md5Hash(admin.getPassword(), salt, 1024);
        admin.setPassword(md5Pwd.toHex());
        am.insert(admin);
    }

    @Override
    @LogAnnotation(type = "delete",value = "删除管理员")
    public void deleteAdmin(Integer id) {
        am.deleteById(id);
    }

    @Override
    @LogAnnotation(type = "update",value = "修改管理员")
    public void updateAdmin(CmfzAdmin admin) {
        String salt = UUID.randomUUID().toString().substring(0, 4);
        admin.setSalt(salt);
        Md5Hash md5Pwd = new Md5Hash(admin.getPassword(), salt, 1024);
        admin.setPassword(md5Pwd.toHex());
        am.updateById(admin);
    }

    @Override
    public CmfzAdmin selectById(Integer id) {
        return am.selectById(id);
    }

    @Override
    public CmfzAdmin selectByName(String username) {
        return am.selectOne(new QueryWrapper<CmfzAdmin>().eq("username",username));
    }

    @Override
    public IPage<CmfzAdmin> selectAdminAndRole(Integer page, Integer limit) {
        Page<CmfzAdmin> page1 = new Page<>(page, limit);
        IPage<CmfzAdmin> pi = am.selectAdminAndRole(page1, null);
        return pi;
    }
}
